package edu.whu.rose.clock.ssql.util;

public class StrLinkedList {

	private StrLinkedNode head;
	private StrLinkedNode end;
	
	public StrLinkedList() {
		this(null);
	}
	
	public StrLinkedList(StrLinkedNode head) {
		this.head = head;
		this.end = head;
	}
	
	public void insertAtEnd(StrLinkedNode node) {
		if (end == null) {
			head = node;
			end = node;
		}
		else {
			end.setNext(node);
			end = node;
		}
	}
	
	public void switchToEnd(String keyword) {
		StrLinkedNode sln = head;
		if (sln.getKeyword().equals(keyword)) {
			if (sln.getNext() != null) {
				head = sln.getNext();
				end.setNext(sln);
				end = sln;
			}
			return;
		}
		for (; sln.getNext() != null && !sln.getNext().getKeyword().equals(keyword); sln = sln.getNext());
		if (sln.getNext() == null) {
			System.out.println("Error: found keyword (" + keyword + ") in cache but not in queue");
			return;
		}
		StrLinkedNode temp = sln.getNext();
		if (temp != end) {
			sln.setNext(temp.getNext());
			end.setNext(temp);
			end = temp;
		}
	}
	
	public StrLinkedNode removeHead() {
		StrLinkedNode sln = head;
		if (head == end) {
			head = null;
			end = null;
		}
		else {
			head = head.getNext();
		}
		
		return sln;
	}
	
	public void delete(String keyword) {
		StrLinkedNode sln = head;
		if (sln.getKeyword().equals(keyword)) {
			if (end == head) {
				head = null;
				end = null;
			}
			else {
				head = head.getNext();
			}
			return;
		}
		for (; sln.getNext() != null && !sln.getNext().getKeyword().equals(keyword); sln = sln.getNext());
		if (sln.getNext() == null) {
			System.out.println("Error: found keyword (" + keyword + ") in cache but not in queue");
			return;
		}
		sln.setNext(sln.getNext().getNext());
	}
	
	public void deleteAtEnd(String keyword) {
		if (end != null && end.getKeyword().equals(keyword)) {
			StrLinkedNode sln = head;
			if (sln == end) {
				head = null;
				end = null;
				return;
			}
			for (; sln.getNext() != end; sln = sln.getNext());
			sln.setNext(null);
			end = sln;
		}
		else {
			System.out.println("Error: cannot find the correct end of the queue");
		}
	}
	
}
